// 导入express包
var express = require('express')
// 实例化路由对象
var router = express.Router()

// 编写路由规则

// 导入操作数据库的方法
const { getAll, getOne, exec } = require('../db/index')

// 解构调试的标记,将来会根据这个标记来决定是否打印错误信息
const { debug } = require('../config/index')

// 获取所有待办事项
router.get('/', async function (req, res) {
  let sql = `select * from vue_todos`
  const data = await getAll(sql)
  res.send({
    code: 0,
    msg: '获取所有待办成功',
    result: data,
  })
})

//获取单个待办事项
router.get('/:id', async function (req, res) {
  // 解析请求参数
  const id = req.params.id
  // 操作数据库
  let sql = `select * from vue_todos where id = ${id}`
  const data = await getById(sql)
  // 返回结果
  if (data != null) {
    res.send({
      code: 0,
      msg: `获取id为${id}的待办成功`,
      result: data,
    })
  }
})

// 新增待办事项
router.post('/finish', async function (req, res) {
  const { content } = req.body
  let sql = `insert into vue_todos (content) values('${content}')`
  const data = await exec(sql)
  const id = data.insertId
  let sql1 = `select * from vue_todos where id=${id}`
  const resData = await getById(sql1)
  res.send({
    code: 0,
    msg: '添加待办成功',
    result: resData,
  })
})

// 修改待办
router.put('/:id', async function (req, res) {
  const id = req.params.id
  const { content, completed } = req.body
  let sql = `update vue_todos set content='${content}',completed=${completed} where id = ${id}`
  const data = await exec(sql)
  let sql1 = `select * from vue_todos where id = ${id}`
  const resData = await getById(sql1)
  res.send({
    code: 0,
    msg: '修改待办事项成功',
    result: resData,
  })
})
// 删除待办
router.delete('/:id', async function (req, res) {
  const id = req.params.id

  let sql = `delete from vue_todos where id = ${id}`
  const data = await exec(sql)
  res.send({
    code: 0,
    msg: `删除id为${id}待办事项成功`,
    result: '',
  })
})

// 删除所有已办事项
router.delete('/', async function (req, res) {
  const { completed } = req.query
  let sql = `delete from vue_todos where completed = ${completed}`
  const data = await exec(sql)
  res.send({
    code: 0,
    msg: '删除所有已办事项成功',
    result: '',
  })
})
// 导出路由对象
module.exports = router
